package com.xbongbong.paas.toolbox.util;

import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.wrap.QueryIgnore;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.BeansException;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.BiConsumer;

/**
 * bean工具类
 * @author kaka
 * @time 2018-8-29 17:19
 */
public class BeanUtil {

    private static final Logger LOG = LoggerFactory.getLogger(BeanUtil.class);

    /**
     * 拷贝实体，source,targetClass不允许为空
     * @param source 被拷贝实体
     * @param targetClass 拷贝目标实体的class
     * @param ignoreNull 是否忽略null值，设为true时会跳过sourceObject中的null值 by kaka
     * @return T 拷贝目标实体，即targetClass对应的对象
     * @throws XbbException
     * @author zcp
     * @date 2019/4/1 18:47
     * @since v1.0
     * @version v1.0
     */
    public static <T> T copyProperties(Object source, Class<T> targetClass, boolean ignoreNull) throws XbbException {
        T target;
        try {
            target = targetClass.newInstance();
        } catch (Exception e) {
            LOG.error("返回泛型T方法copyProperties 出现错误", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
        copyPropertiesIgnoreNull(source, target, ignoreNull);
        return target;
    }
    /**
     * 拷贝实体，source,target不允许为空
     * @param source 被拷贝实体
     * @param target 拷贝目标实体
     * @param ignoreNull 是否忽略null值，设为true时会跳过sourceObject中的null值 by kaka
     */
    public static void copyProperties(Object source, Object target, boolean ignoreNull) {
        copyPropertiesIgnoreNull(source, target, ignoreNull);
    }

    /**
     * 拷贝实体，source,target不允许为空
     * 跳过null值
     * @param source 被拷贝实体
     * @param target 拷贝目标实体
     */
    public static void copyProperties(Object source, Object target) {
        copyProperties(source, target, true);
    }

    /**
     * 拷贝实体集合，sourceList
     * 只支持自定义实体集合拷贝
     * 应用场景：DTO <=> DO 等
     * @param sourceList 被拷贝列表
     * @param targetList 拷贝目标列表
     * @param clazz 拷贝目标类型
     */
    public static <S,T>  void copyPropertiesList(List<S> sourceList, List<T> targetList, Class<T> clazz, BiConsumer<S,T> function) throws InstantiationException,IllegalAccessException,XbbException {
        if (sourceList == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100015);
        }
        for (S items : sourceList) {
            T target =  clazz.newInstance();
            copyProperties(items, target, true);
            function.accept(items,target);
            targetList.add(target);
        }
    }


    /**
     * 拷贝实体集合，sourceList
     * 只支持自定义实体集合拷贝
     * 应用场景：DTO <=> DO 等
     * @param sourceList 被拷贝列表
     * @param targetList 拷贝目标列表
     * @param clazz 拷贝目标类型
     * @param ignoreNull 是否忽略null值，设为true时会跳过sourceObject中的null值 by kaka
     */
    public static void copyPropertiesList(List sourceList, List targetList, Class clazz, boolean ignoreNull) throws InstantiationException,IllegalAccessException,XbbException {
        if (sourceList == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100015);
        }
        for (Object items : sourceList) {
            Object target = clazz.newInstance();
            copyProperties(items, target, ignoreNull);
            targetList.add(target);
        }
    }

    /**
     * 拷贝实体集合，sourceList,忽略null字段
     * 只支持自定义实体集合拷贝
     * 应用场景：DTO <=> DO 等
     * @param sourceList 被拷贝列表
     * @param targetList 拷贝目标列表
     * @param clazz 拷贝目标类型
     */
    public static void copyPropertiesList(List sourceList, List targetList, Class clazz) throws InstantiationException,IllegalAccessException,XbbException {
        copyPropertiesList(sourceList, targetList, clazz, true);
    }

    /**
     * Map --> Bean 1: 利用Introspector,PropertyDescriptor实现 Map --> Bean
     *
     * @param map 需要被转化的map
     * @param obj 转化目标obj
     */
    public static void convertMap2Bean(Map<String, Object> map, Object obj) throws IntrospectionException, InvocationTargetException, IllegalAccessException {
        BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();

        for (PropertyDescriptor property : propertyDescriptors) {
            String key = property.getName();
            if (map.containsKey(key)) {
                Object value = map.get(key);
                // 得到property对应的setter方法
                Method setter = property.getWriteMethod();
                setter.invoke(obj, value);
            }
        }
    }


    /**
     * Bean --> Map 1: 利用Introspector和PropertyDescriptor 将Bean --> Map, 不检查查询忽略标签
     *
     * @param obj 被转化的javaBean
     */
    public static Map<String, Object> convertBean2Map(Object obj) throws XbbException {
        return convertBean2Map(obj, false);
    }

    /**
     * Bean --> Map 1: 利用Introspector和PropertyDescriptor 将Bean --> Map
     *
     * @param obj 被转化的javaBean
     * @param queryIgnore 是否检查查询忽略标签
     */
    public static Map<String, Object> convertBean2Map(Object obj, boolean queryIgnore) throws XbbException{

        if (obj == null) {
            return null;
        }
        Map<String, Object> map = new HashMap<>(16);
        BeanInfo beanInfo = null;
        try {
            beanInfo = Introspector.getBeanInfo(obj.getClass());
        } catch (IntrospectionException e) {
            LOG.error("convertBean2Map 出现错误", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor property : propertyDescriptors) {
            String key = property.getName();

            // 过滤class属性
            if ("class".equals(key)) {
                continue;
            }

            // 得到property对应的getter方法
            Method getter = property.getReadMethod();
            //检查查询忽略标签
            if(queryIgnore) {
                boolean ignore = getter.isAnnotationPresent(QueryIgnore.class);
                if(ignore) {
                    continue;
                }
            }
            Object value = null;
            try {
                value = getter.invoke(obj);
            } catch (IllegalAccessException | InvocationTargetException e) {
                LOG.error("convertBean2Map 出现错误", e);
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
            }

            map.put(key, value);
        }
        return map;
    }

    public static Map<String, Object> convertBean2Map(Object obj, boolean queryIgnore,boolean nullIgnore) throws XbbException{

        if (obj == null) {
            return null;
        }
        Map<String, Object> map = new HashMap<>(16);
        BeanInfo beanInfo = null;
        try {
            beanInfo = Introspector.getBeanInfo(obj.getClass());
        } catch (IntrospectionException e) {
            LOG.error("convertBean2Map 出现错误", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor property : propertyDescriptors) {
            String key = property.getName();

            // 过滤class属性
            if ("class".equals(key)) {
                continue;
            }

            // 得到property对应的getter方法
            Method getter = property.getReadMethod();
            //检查查询忽略标签
            if(queryIgnore) {
                boolean ignore = getter.isAnnotationPresent(QueryIgnore.class);
                if(ignore) {
                    continue;
                }
            }
            Object value = null;
            try {
                value = getter.invoke(obj);
            } catch (IllegalAccessException | InvocationTargetException e) {
                LOG.error("convertBean2Map 出现错误", e);
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
            }
            //跳过值为null的属性
            if(nullIgnore && value == null){
                continue;
            }

            map.put(key, value);
        }
        return map;
    }

    /**
     * 将list转为map,指定list中的实体的某个成员域作为key，该成员域为value
     * @param list 需要被转成map的list
     * @param keyField 指定list实体中的keyField作为key
     * @param <K> map 的 key 类型，与keyField类型相同
     * @param <V> map 的 value 类型,与list的成员类型相同
     * @return 转换后的map
     * @author kaka
     * @time 2018-9-4 18:00
     */
    public static <K,V> Map<K,V> convertListToMap(List<V> list, String keyField) throws XbbException{
        Map<K,V> result = new HashMap<>(16);
        if(list != null && list.size() > 0 && !StringUtil.isEmpty(keyField)){
            String firstLetter = keyField.substring(0, 1).toUpperCase();
            String getter = "get" + firstLetter + keyField.substring(1);
            try {
                for(Object obj : list){
                    Method method = obj.getClass().getMethod(getter,null);
                    K key = (K) method.invoke(obj,null);
                    if(key != null){
                        result.put(key,(V) obj);
                    }
                }
            } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
                LOG.error("convertListToMap 出错", e);
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
            }
        }
        return result;
    }

    //==================== 在 spring 原方法上做了修改 ====================

    /**
     * 本方法基于Spring的BeanUtils实现，替换原来的实现
     * 原方法效率比本方法在大量调用时效率有较大优势（ignoreNull=true时100W次调用约4倍），但是导致了内存占用没有回收问题
     * 故先改为该实现
     * @param source 被拷贝实体
     * @param target 拷贝目标实体
     * @param ignoreNull 是否忽略null值
     * @throws BeansException 异常
     */
    public static void copyPropertiesIgnoreNull(Object source, Object target, boolean ignoreNull) throws BeansException {
        String[] nullPropertyNames = null;
        if (ignoreNull) {
            nullPropertyNames = getNullPropertyNames(source);
        }
        BeanUtils.copyProperties(source, target, nullPropertyNames);
    }

    /**
     * 获取object中的null值属性，后续进行copy的时候忽略这些属性
     * @param source 原对象实体
     * @return 值为null的属性名数组
     */
    private static String[] getNullPropertyNames (Object source) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();

        Set<String> emptyNames = new HashSet<>();
        for(java.beans.PropertyDescriptor pd : pds) {
            if (pd.getReadMethod() == null) {
                continue;
            }
            Object srcValue;
            try {
                srcValue = src.getPropertyValue(pd.getName());
            } catch (Exception ite) {
//                LOG.error("请检查相关反射实体方法，尤其是is和get方法", ite);
                continue;
            }
            if (srcValue == null) {
                emptyNames.add(pd.getName());
            }
        }
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }
}
